package com.young.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author ：young
 * @date ：Created in 2019/7/6
 * @description：somting
 */
@RestController
@RequestMapping(value = "/consumer")
public class RestTempleteController {
    @Autowired
    RestTemplate restTemplate;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String helloConsumer() {
        return restTemplate.getForEntity("http://app/app/hello", String.class).getBody();
    }

    @RequestMapping(value = "/mutilpartFile", method = RequestMethod.POST)
    public String mutilpartFile(@RequestParam("file") MultipartFile file) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        RestTemplate client = new RestTemplate();
        MultiValueMap<String, Object> body
                = new LinkedMultiValueMap<>();
        try {
            body.add("file", file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity<MultiValueMap<String, Object>> requestEntity
                = new HttpEntity<>(body, headers);
        String serverUrl = "http://127.0.0.1:9528/app/mutilpartFile";
        ResponseEntity<String> response = client
                .postForEntity(serverUrl, requestEntity, String.class);
        return file.getOriginalFilename();
    }
}
